
"""
    用户
"""

from rest_framework import serializers
from users.models import UserProfileModel, Organization, Role
import re


class UserProfileModelListSerializer(serializers.ModelSerializer):
    """
    用户列表序列化
    """
    department_name = serializers.CharField(source='department')
    date_joined = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)

    class Meta:
        model = UserProfileModel
        fields = ('id', 'avatar', 'username', 'name', 'mobile', 'email', 'department_name', 'position', 'is_active',
                  'date_joined')


class UserProfileModelRetrieveViewSerializer(serializers.ModelSerializer):
    """
    用户详情序列化
    """

    class Meta:
        model = UserProfileModel
        fields = ('id', 'avatar', 'username', 'name', 'mobile', 'email', 'department', 'position', 'is_active',
                  'roles', 'superior', 'introduction')

    def to_representation(self, instance):
        """
        修改序列化前的数据格式
        :param instance:
        :return:
        """
        role_list = []
        data = super().to_representation(instance)
        if data['department']:
            department = Organization.objects.filter(id=data['department']).first()
            if department:
                data['department'] = [department.id]
                if department.pid:
                    data['department'] = [department.pid.id, department.id]
                    if department.pid.pid:
                        data['department'] = [department.pid.pid.id, department.pid.id, department.id]
                        if department.pid.pid.pid:
                            data['department'] = [department.pid.pid.pid.id, department.pid.pid.id, department.pid.id,
                                                  department.id]
                            if department.pid.pid.pid.pid:
                                data['department'] = [department.pid.pid.pid.pid.id, department.pid.pid.pid.id,
                                                      department.pid.pid.id, department.pid.id, department.id]
                                if department.pid.pid.pid.pid.pid:
                                    data['department'] = [department.pid.pid.pid.pid.pid.id,
                                                          department.pid.pid.pid.pid.id,
                                                          department.pid.pid.pid.id, department.pid.pid.id,
                                                          department.pid.id,
                                                          department.id]
                                    if department.pid.pid.pid.pid.pid.pid:
                                        data['department'] = [department.pid.pid.pid.pid.pid.pid.id,
                                                              department.pid.pid.pid.pid.pid.id,
                                                              department.pid.pid.pid.pid.id,
                                                              department.pid.pid.pid.id, department.pid.pid.id,
                                                              department.pid.id,
                                                              department.id]

        if data['superior']:
            sup = UserProfileModel.objects.filter(id=data['superior']).first()
            if sup.id:
                data['superior'] = [sup.department.id, sup.id]
                if sup.department.pid:
                    data['superior'] = [sup.department.pid.id, sup.department.id, sup.id]
                    if sup.department.pid.pid:
                        data['superior'] = [sup.department.pid.pid.id, sup.department.pid.id, sup.department.id, sup.id]
                        if sup.department.pid.pid.pid:
                            data['superior'] = [sup.department.pid.pid.pid.id, sup.department.pid.pid.id,
                                                sup.department.pid.id, sup.department.id, sup.id]
                            if sup.department.pid.pid.pid.pid:
                                data['superior'] = [sup.department.pid.pid.pid.pid.id, sup.department.pid.pid.pid.id,
                                                    sup.department.pid.pid.id, sup.department.pid.id, sup.department.id,
                                                    sup.id]
                                if sup.department.pid.pid.pid.pid.pid:
                                    data['superior'] = [sup.department.pid.pid.pid.pid.pid.id,
                                                        sup.department.pid.pid.pid.pid.id,
                                                        sup.department.pid.pid.pid.id, sup.department.pid.pid.id,
                                                        sup.department.pid.id, sup.department.id, sup.id]
                                    if sup.department.pid.pid.pid.pid.pid.pid:
                                        data['superior'] = [sup.department.pid.pid.pid.pid.pid.id,
                                                            sup.department.pid.pid.pid.pid.id,
                                                            sup.department.pid.pid.pid.id, sup.department.pid.pid.id,
                                                            sup.department.pid.id, sup.department.id, sup.id]
                                        if sup.department.pid.pid.pid.pid.pid.pid.pid:
                                            pass
                                        else:
                                            data['superior'] = [sup.department.pid.pid.pid.pid.pid.pid.id,
                                                                sup.department.pid.pid.pid.pid.pid.id,
                                                                sup.department.pid.pid.pid.pid.id,
                                                                sup.department.pid.pid.pid.id,
                                                                sup.department.pid.pid.id,
                                                                sup.department.pid.id, sup.department.id, sup.id]

        if data['roles']:
            roles = Role.objects.filter(id__in=data['roles'])
            for ro in roles:
                if ro.department.pid:
                    if ro.department.pid.pid:
                        if ro.department.pid.pid.pid:
                            if ro.department.pid.pid.pid.pid:
                                if ro.department.pid.pid.pid.pid.pid:
                                    if ro.department.pid.pid.pid.pid.pid.pid:
                                        if ro.department.pid.pid.pid.pid.pid.pid.pid:
                                            pass
                                        else:
                                            role_list.append([ro.department.pid.pid.pid.pid.pid.pid.id,
                                                              ro.department.pid.pid.pid.pid.pid.id,
                                                              ro.department.pid.pid.pid.pid.id,
                                                              ro.department.pid.pid.pid.id, ro.department.pid.pid.id,
                                                              ro.department.pid.id, ro.department.id, ro.id])
                                    else:
                                        role_list.append(
                                            [ro.department.pid.pid.pid.pid.pid.id, ro.department.pid.pid.pid.pid.id,
                                             ro.department.pid.pid.pid.id, ro.department.pid.pid.id,
                                             ro.department.pid.id, ro.department.id, ro.id])
                                else:
                                    role_list.append([ro.department.pid.pid.pid.pid.id, ro.department.pid.pid.pid.id,
                                                      ro.department.pid.pid.id, ro.department.pid.id,
                                                      ro.department.name, ro.id])
                            else:
                                role_list.append(
                                    [ro.department.pid.pid.pid.id, ro.department.pid.pid.id, ro.department.pid.id,
                                     ro.department.id, ro.id])
                        else:
                            role_list.append([ro.department.pid.pid.id, ro.department.pid.id, ro.department.id, ro.id])
                    else:
                        role_list.append([ro.department.pid.id, ro.department.id, ro.id])
                else:
                    role_list.append([ro.department.id, ro.id])
            data['roles'] = role_list
            # print(role_list)
        return data


class UserProfileModelCreateSerializer(serializers.ModelSerializer):
    """
    创建用户序列化
    """
    username = serializers.CharField(required=True, allow_blank=False)
    mobile = serializers.CharField(max_length=11)

    class Meta:
        model = UserProfileModel
        fields = ['id', 'avatar', 'username', 'name', 'mobile', 'email', 'department', 'position', 'is_active', 'roles',
                  'superior', 'introduction', 'password']

    def validate_username(self, username):
        if UserProfileModel.objects.filter(username=username):
            raise serializers.ValidationError(username + ' 账号已存在')
        return username

    def validate_mobile(self, mobile):
        REGEX_MOBILE = "^1[358]\d{9}$|^147\d{8}$|^176\d{8}$"
        if not re.match(REGEX_MOBILE, mobile):
            raise serializers.ValidationError("手机号码不合法")
        if UserProfileModel.objects.filter(mobile=mobile):
            raise serializers.ValidationError("手机号已经被注册")
        return mobile


class UserProfileModelUpdateSerializer(serializers.ModelSerializer):
    """
    用户编辑的序列化
    """
    mobile = serializers.CharField(max_length=11)

    class Meta:
        model = UserProfileModel
        fields = ['id', 'avatar', 'name', 'mobile', 'email', 'department', 'position', 'is_active', 'roles', 'superior',
                  'introduction']

    def validate_mobile(self, mobile):
        REGEX_MOBILE = "^1[358]\d{9}$|^147\d{8}$|^176\d{8}$"
        if not re.match(REGEX_MOBILE, mobile):
            raise serializers.ValidationError("手机号码不合法")
        return mobile


class UserProfileModelExportSerializer(serializers.ModelSerializer):
    """
    导出用户表序列化
    """
    date_joined = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)

    class Meta:
        model = UserProfileModel
        fields = ('id', 'username', 'name', 'mobile', 'email', 'department', 'position', 'is_active', 'roles',
                  'superior', 'date_joined', 'introduction')

    def to_representation(self, instance):
        """
        修改序列化前的数据格式
        :param instance:
        :return:
        """
        data = super().to_representation(instance)

        # 部门
        if data['department'] is None:
            data['department'] = ''
        else:
            obj = Organization.objects.filter(id=data['department']).values('id', 'name').first()
            data['department'] = obj['name']

        # 上级主管
        if data['superior'] is None:
            data['superior'] = ''
        else:
            obj = UserProfileModel.objects.filter(id=data['superior']).values('id', 'name').first()
            data['superior'] = obj['name']

        # 状态
        if data['is_active'] is True:
            data['is_active'] = '激活'
        else:
            data['is_active'] = '锁定'

        # 角色
        roles_name = ''
        if data['roles']:
            obj = UserProfileModel.objects.filter(id=data['id']).first()
            obj_roles = obj.roles.all()
            for i in obj_roles:
                if roles_name:
                    roles_name = roles_name + ', ' + i.name
                else:
                    roles_name = i.name
            data['roles'] = roles_name
        else:
            data['roles'] = ''

        return data
